package com.ikaros.service.impl;

import com.ikaros.dao.ProductInfoDao;
import com.ikaros.dto.CartDTO;
import com.ikaros.entity.ProductInfo;
import com.ikaros.enums.ProductStatusEnum;
import com.ikaros.enums.ResultEnums;
import com.ikaros.exception.SellException;
import com.ikaros.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by Ikaros on 2017/9/10.
 */
@Service
public class ProductServiceImpl implements ProductService{
    @Autowired
    private ProductInfoDao productInfoDao;
    @Override
    public ProductInfo findOne(String categoryId) {
        return productInfoDao.findOne(categoryId);
    }

    @Override
    public List<ProductInfo> findUpAll() {
        return productInfoDao.findByProductStatus(ProductStatusEnum.up.getCode());
    }

    @Override
    public Page<ProductInfo> findAll(Pageable pageable) {
        return productInfoDao.findAll(pageable);
    }

    @Override
    public ProductInfo save(ProductInfo productInfo) {
        return productInfoDao.save(productInfo);
    }

    @Override
    @Transactional
    public void increaseStock(List<CartDTO> cartDTOList) {
        for (CartDTO cartDTO:cartDTOList){
            ProductInfo productInfo = productInfoDao.findOne(cartDTO.getProductId());
            if (productInfo==null){
                throw new SellException(ResultEnums.ORDERDETAIL_NOT_EXIST);
            }
            Integer result=productInfo.getProductStock()+cartDTO.getProductQuantity();
            productInfo.setProductStock(result);
            productInfoDao.save(productInfo);
        }
    }

    @Override
    @Transactional
    public void decreaseStock(List<CartDTO> cartDTOList) {
        //todo:扣库存高并发：超卖
        for (CartDTO cartDTO:cartDTOList) {
            ProductInfo productInfo = productInfoDao.findOne(cartDTO.getProductId());
            //思考：如果只是创建订单的话：这里可以不进行判断，但是这是扣库存方法，不仅创建订单使用
            if (productInfo==null){
                throw new SellException(ResultEnums.PRODUCT_NOT_EXIST);
            }
            Integer result=productInfo.getProductStock()-cartDTO.getProductQuantity();
            if (result<0){
                throw new SellException(ResultEnums.PRODUCT_STOCK_ERROR);
            }
            productInfo.setProductStock(result);
            productInfoDao.save(productInfo);
        }
    }
}
